import { ref } from 'vue'
import type { Ref } from 'vue'
import { defineStore } from 'pinia'
import { getUserInfoServer } from '@/api/server/user'
import { darkTheme } from 'naive-ui'
import { useDark, useToggle } from '@vueuse/core'
import { logoutServer } from '@/api/server/account'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore(
  'yqbj-user',
  () => {
    //用户登录凭证管理
    const token: Ref<any> = ref(null)
    const setToken = (value: any) => {
      token.value = value
    }
    const removeToken = () => {
      token.value = null
    }
    // 用户信息管理
    const user: Ref<any> = ref(null)
    const getUser = async () => {
      const res = await getUserInfoServer()
      user.value = res?.data
    }
    const setUser = (userInfo: any) => {
      user.value = userInfo
    }
    const logout = async () => {
      removeToken()
      user.value = null
      const res = await logoutServer()
      console.log(res)
    }
    // 用户theme 选择  默认黑暗模式
    const isDark: Ref<boolean> = ref(true)
    const theme: Ref<any> = ref(darkTheme)
    const elDark = useDark()
    const toggleDark = useToggle(elDark)
    const changeTheme = () => {
      elDark.value = isDark.value
      toggleDark()
      isDark.value = !isDark.value
      isDark.value ? (theme.value = darkTheme) : (theme.value = null)
    }
    return {
      token,
      setToken,
      removeToken,
      user,
      getUser,
      setUser,
      logout,
      isDark,
      theme,
      changeTheme
    }
  },
  {
    persist: true
  }
)
